/*
 * The client finder and the holder of the Client Port at
 * the end of the Client Port finding procedure
*/

package com.costeaalex.blueserver.comm;

import java.util.ArrayList;
import java.util.Enumeration;

import javax.comm.*;

import com.costeaalex.blueserver.setup.SetupServerApp;
import com.costeaalex.blueserver.timeout.TimeoutProcess;

public class COMPortClientFinder implements TimeoutProcess
	{
	
	private CommPort cP=null;
	private CommPort clientCP;
	private Enumeration<CommPortIdentifier> portList;
	private COMPortClientCheck cC;
	private COMPortClientFound cPCF;
	private ArrayList<COMPortClientCheck> portsThreads=new ArrayList<COMPortClientCheck>(50);
	private SetupServerApp sSL;
	private boolean cancellable=true;
	private boolean startEnded=false;
	private String name="COMPortClientFinder";
	
	private static CommPortIdentifier cPI;
	
	public COMPortClientFinder(SetupServerApp sS)
		{
		sSL=sS;
		cPCF=new COMPortClientFound(this, sS);
		}
	
	@SuppressWarnings("unchecked")
	public void start()
		{
		int i=1;
		
		cPCF.start();
		portList=CommPortIdentifier.getPortIdentifiers();
		
		while(portList.hasMoreElements())
			{
			cPI=portList.nextElement();
			if(cPI.getPortType()==1 && cancellable)
				{
				try
					{
					cP=cPI.open("Java Blue Remote Client Finder", 3000);
					cC=new COMPortClientCheck(this, cP, "Thread COM Port Finder "+i);
					portsThreads.add(i-1,cC);
					//System.out.println(portsThreads.size()+" - "+cC.getName());
					cC.start();
					} 
				catch (PortInUseException e)
					{
					e.printStackTrace();
					}
				System.out.println(cPI.getName()+" opened");		
				}
			i++;
			}
		
		startEnded=true;
		sSL.portsOpened();
		}
	
	public synchronized void foundPort(CommPort cPort)
		{
		cPort.close();
		clientCP=cPort;
		}
	
	public CommPort getPort()
		{
		return clientCP;
		}
	
	public void destroy()
		{
		int i;
		
		cancellable=false;
		
		while(startEnded==false)
			{}
		
		for(i=0; i<portsThreads.size();i++)
			{
			//System.out.println(portsThreads.get(i).getName()+"-"+i);
			portsThreads.get(i).closePort();
			}
		
		}

	public boolean isCancellable()
		{
		return cancellable;
		}

	public String getProcessName()
		{
		return name;
		}
	
	}
